<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动售卖机</title>
    <style>
        ul {
            list-style-type: none; /* 去除项目符号 */
            margin: 0;             /* 去除默认外边距 */
            padding: 0;            /* 去除默认内边距 */
            }

            li {
            margin: 0;             /* 去除默认外边距 */
            padding: 0;            /* 去除默认内边距 */
            }
        body {
            font-family: 'Open Sans', sans-serif;
            margin: 0;
            padding: 0;
        }

        .main {
            width: 60%;
            margin: auto;
        }

        .navbar {
            background-color: #4CAF50;
            overflow: hidden;
            width: 100%;
            padding: 20px;
            border-radius: 10px 10px 0px 0px;
        }

        .navbar a {
            float: left;
            display: block;
            color: white;
            padding: 14px 10px;
            text-align: center;
            text-decoration: none;
            transition: background-color 0.3s;
        }

        .navbar a:hover {
            background-color: #45a049;
        }

        .container {
            width: 100%;
            padding: 20px;
            background-color: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .goods {
            display: none;
            flex-wrap: wrap;
            width: 100%;
            margin-bottom: 30px;
        }

        .goods-item {
            width: 20%;
            margin: 11px;
            text-align: center;
            border-radius: 10px;
            border: 1px solid #45a049;
            padding: 10px;
        }

        .img {
            text-align: center;
        }

        .img img {
            width: 80%;
            height: 80%;
            object-fit: cover;
        }

        .description {
            margin: 10px 20px;
            font-size: small;
            text-align: left;
        }

        .buy {
            display: flex;
            justify-content: space-between;
            cursor: pointer;
            font-size: small;
            margin: 0px 20px;
        }

        .price {
            color: #c52b77;
        }

        .icon {
            display: flex;
        }

        .icon span {
            margin-left: 20px;
        }

        .icon img {
            margin-left: 20px;
            width: 20px;
            height: 20px;
        }

        .buttom {
            width: 100%;
            height: 50px;
            text-align: center;
            color: #45a049;
        }

        #timer {
            float: left;
            width: 50px;
            height: 50px;
            border: 1px solid #45a049;
            border-radius: 10px;
            display: none;
            margin-left: 10px;
            line-height: 50px;
            font-size: large;
        }

        #checkGoods {
            width: 10%;
            float: right;
            padding: 15px;
            margin-right: 20px;
            border-radius: 5px;
            border: 1px solid #45a049;
        }

        #shoppingCart {
            display: flex;
            width: 10%;
            float: right;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #45a049;
             cursor: pointer;
        }

        #shoppingCart img {
            width: 15px;
            height: 15px;
            margin-right: 5px;
            margin-top: 4px;
           
        }

        #shoppingCart .number {
            text-align: center;
            font-size: small;
            font-weight: lighter;
            display: none;
            width: 20px;
            height: 20px;
            line-height: 20px;
            border-radius: 20px;
            color: white;
            background-color: red;
            position: relative;
            top: -20px;
            right: -20px;
        }


        /* 购物车详细页面展示 */
        .screen {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
        }

        #shoppingCartDetails {
            position: absolute;
            text-align: center;
            width: 500px;
            height: 500px;
            background-color: #f3eae6;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
        
        .goodsImg, .goodsImg>img {
            width: 50px;
            height: 50px;
        }

        table {
            margin: 0 auto;
        }
        td,th {
            width: 100px;
            text-align: center;
        }
     
        .left {
            transform: translateX(-15px);
             width: 20px;
            height: 20px;
            vertical-align:bottom;
        }
        .right {
            transform: translateX(15px);
             width: 20px;
            height: 20px;
            vertical-align:bottom;
        }
        .goodsPrice {
            width: 150px;
        }

        /* 结算 */
        .settle {
            position: fixed;
            bottom: 10px;
            right: 30px;
            font-size:25px;
            display: flex;
        }

        .settle .money {
            color: #c52b77;
        }

        .jiesuan {
            width: 80px;
            height: 30px;
            margin-left: 10px;
            background-color: #45a049;
            /* border: black 1px solid; */
            box-shadow: black 1px 1px ;
            cursor: pointer;
        }

        .jiesuan:active {
            box-shadow: black 2px 2px ;
        }
    </style>
    
</head>

<body>
    <div class="main" >
        <div class="navbar">
            <!-- 从这里传入你所点击的东西 all DailyProducts-->
            <a href="javascript:void(0)" onclick="showProduct('all')">全部</a>
            <a href="javascript:void(0)" onclick="showProduct('DailyProducts')">日化用品</a>
            <a href="javascript:void(0)" onclick="showProduct('CakeBread')">蛋糕面包</a>
            <a href="javascript:void(0)" onclick="showProduct('SnackFoods')">休闲食品</a>
            <a href="javascript:void(0)" onclick="showProduct('Milk')">牛奶乳品</a>
        </div>

        <div class="container">
            <div id="all" class="goods">
            </div>
            <div id="DailyProducts" class="goods">
            </div>
            <div id="CakeBread" class="goods">
            </div>
            <div id="SnackFoods" class="goods">
            </div>
            <div id="Milk" class="goods">
            </div>
            <div class="buttom">
                <div id="timer"></div>
                <div id="shoppingCart">
                    <img src="./icon/购物车.png" alt="购物车">
                    购物车
                    <div id="number" class="number"></div>
                </div>
                <div id="checkGoods">意见反馈</div>
            </div>

        </div>

    </div>

      <div class="screen">
        <div id="shoppingCartDetails">
        <!-- 购物车详情将在这里显示 -->
            <!-- <ul class="shopCar_list">
                <li class="shopCar_item">
                    <img src="./img/OIP-C.jpg" alt="">
                    <span class="goodName">1324561</span>
                    <span class="price">123</span>
                    <span class="count">123</span>
                </li>
            </ul> -->
            <table border="1">
                <th>商品图片</th>
                <th>商品名称</th>
                <th>商品价格</th>
                <th >商品数量</th>
                <tr>
                    <td class="goodsImg">  <img src="./img/OIP-C.jpg" alt=""></td>
                    <td class="goodsName">苏打水</td>
                    <td class="goodsPrice"><img id="icon" class="left" src="./icon/减号.png" alt="">12<img id="icon" class="right" src="./icon/加号.png" alt=""></td>
                    <td class="count">12</td>
                </tr>
            </table>
            <!-- 结账 -->
            <div class="settle"><span class="total">总金额: <span class="money">15</span>元 </span> <div class="jiesuan">结账</div></div>
        </div>
      </div>
</body>
<script>
        var goodsData = [
            {
             id: 1,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "DailyProducts",  //商品名称,
            price: 5.30,	//价格
	        classify:'DailyProducts'  //DailyProducts CakeBread SnackFoods  Milk
            },
            {
             id: 2,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "苏打水",  //商品名称,
            price: 5.30,	//价格
	        classify:'DailyProducts'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 3,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "CakeBread",  //商品名称,
            price: 5.30,	//价格
	        classify:'CakeBread'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 4,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "苏打水",  //商品名称,
            price: 5.30,	//价格
	        classify:'CakeBread'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 5,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "SnackFoods",  //商品名称,
            price: 5.30,	//价格
	        classify:'SnackFoods'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 6,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "苏打水",  //商品名称,
            price: 5.30,	//价格
	        classify:'SnackFoods'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 7,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "DailyProducts",  //商品名称,
            price: 5.30,	//价格
	        classify:'DailyProducts'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 8,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "苏打水",  //商品名称,
            price: 5.30,	//价格
	        classify:'Milk'  //DailyProducts CakeBread SnackFoods  Milk
            }, {
             id: 9,		//识别id
            userSelected: 0,  //用户选中数量 方便加入购物车
            inventory: 10 , //剩余库存
            imgURL: "./img/OIP-C.jpg",  	//商品图片
            discription: "Milk",  //商品名称,
            price: 5.30,	//价格
	        classify:'Milk'  //DailyProducts CakeBread SnackFoods  Milk
            },
        ];
        let groupedData = goodsData.reduce((acc, item) => {
            // 根据 item 的 classify 属性来决定将其放入哪个数组
            switch (item.classify) {
                case 'DailyProducts':
                acc.DailyProducts.push(item);
                break;
                case 'CakeBread':
                acc.CakeBread.push(item);
                break;
                case 'SnackFoods':
                acc.SnackFoods.push(item);
                break;
                case 'Milk':
                acc.Milk.push(item);
                break;
                default:
                // 如果有未知分类，可以将其放入一个名为 'Other' 的数组
                acc.Other.push(item);
                break;
            }
            return acc;
            },
                {
                DailyProducts: [],
                CakeBread: [],
                SnackFoods: [],
                Milk: [],
                Other: [] // 用于存放未知分类的商品
                });

        //从data里面获取所有数据
        var DailyProductsData = groupedData.DailyProducts
        var CakeBreadData = groupedData.CakeBread
        var SnackFoodsData = groupedData.SnackFoods
        var MilkData = groupedData.Milk
        var time = 60;
        var goodsCount = 0;
        var timer;
        function display(category) {
            let list = null;
            switch (category) {
                case "DailyProducts": list = DailyProductsData; break;
                case "CakeBread": list = CakeBreadData; break;
                case "SnackFoods": list = SnackFoodsData; break;
                case "Milk": list = MilkData; break;
                default: list = goodsData; break;
            }
            document.getElementById(category).innerHTML = '';
            // 循环渲染商品列表
            list.forEach(function (goods) {
                // console.log(goods);
                
                var goodsListContainer = document.getElementById(category);
                // 创建商品项的HTML结构
                var goodsItem = document.createElement('div');
                goodsItem.className = 'goods-item';

                var imgDiv = document.createElement('div');
                imgDiv.className = 'img';
                var img = document.createElement('img');
                img.src = goods.imgURL;
                img.alt = goods.discription;
                imgDiv.appendChild(img);

                var descriptionDiv = document.createElement('div');
                descriptionDiv.className = 'description';
                descriptionDiv.textContent = goods.discription;

                var buyDiv = document.createElement('div');
                buyDiv.className = 'buy';

                var priceDiv = document.createElement('div');
                priceDiv.className = 'price';
                priceDiv.textContent = '$' + goods.price;

                var iconDiv = document.createElement('div');
                iconDiv.className = 'icon';

                var icon1 = document.createElement('img');
                icon1.src = './icon/加号.png';
                icon1.alt = 'Toggle Quantity';
                icon1.addEventListener("click", function () {
                    increaseCount(countSpan.id,goods.id) //'goodsCount' + goods.id;
                })

                var countSpan = document.createElement('span')
                countSpan.id = 'goodsCount' + goods.id;

                // 让它等于用户选中的数据
                countSpan.innerText = goods.userSelected;

                var icon2 = document.createElement('img');
                icon2.src = './icon/减号.png';
                icon2.alt = 'Toggle Quantity';
                icon2.addEventListener("click", function () {
                    decreaseCount(countSpan.id,goods.id)
                })

                iconDiv.appendChild(icon2);
                iconDiv.appendChild(countSpan);
                iconDiv.appendChild(icon1);


                buyDiv.appendChild(priceDiv);
                buyDiv.appendChild(iconDiv);

                goodsItem.appendChild(imgDiv);
                goodsItem.appendChild(descriptionDiv);
                goodsItem.appendChild(buyDiv);

                // 将商品项添加到商品列表容器中
                goodsListContainer.appendChild(goodsItem);
            });
        }

        window.onload = function () {
            document.getElementById('all').style.display = 'flex';
            display('all');
        }

        // 收取导航栏传过来的东西 all,milk...
        function showProduct(category) {
            var products = document.querySelectorAll('.goods');
            products.forEach(function (product) {
                product.style.display = 'none';
            });
            document.getElementById(category).style.display = 'flex';
            display(category);
        }

        // 倒计时
        function countDown(event) {
            if (timer) {
                clearInterval(timer)
            }
            if (event.button == 0) {
                document.getElementById("timer").style.display = 'block';
                time = 60;
                timer = setInterval(() => {
                    document.getElementById("timer").innerText = time;
                    time--;
                    if (time < 0) {
                        document.getElementById("timer").style.display = 'none';
                        alert("操作超时！")
                        clearInterval(timer);
                    }
                }, 1000)
            }
        }


        // 加
        function increaseCount(goodsID,dataid) {
            countDown(event)
            //获取到元素的id以及元素的所用的数据中的id           
            let goods = document.getElementById(goodsID);
            // 利用dataid给data里面加数据   
            const itemToIncrement = goodsData.find(item => item.id == dataid);
            // 如果找到了该元素，将其 userSelected 加一
            if (itemToIncrement) {
                itemToIncrement.userSelected += 1;
            goods.innerText =  itemToIncrement.userSelected
            }        
            resetGoodsCount()
            if (goodsCount > 0) {
                document.getElementById("number").style.display = 'block';
                document.getElementById("number").innerText = goodsCount;
            }
        }
        //减
        function decreaseCount(goodsID,dataid) {
            countDown(event)
            let goods = document.getElementById(goodsID);
            const itemToIncrement = goodsData.find(item => item.id == dataid);
            // 如果找到了该元素，将其 userSelected 加一
            if (itemToIncrement) {
                if (goodsCount <= 0 || goods.innerText <= 0) {
                alert("Count err!");
                return;
            } else {
                 itemToIncrement.userSelected -= 1;
            goods.innerText =  itemToIncrement.userSelected
            }
            }          
           resetGoodsCount()
            document.getElementById("number").style.display = 'block';
            document.getElementById("number").innerText = goodsCount;
        }

        // 购物车goodsCount重置
       function resetGoodsCount(){
            goodsCount = 0
             goodsData.forEach((data)=>{
            goodsCount += data.userSelected
            })
        }
   
      

       let screen =  document.querySelector('.screen')
      document.getElementById('shoppingCart').addEventListener('click', function() {
        console.log(111);
        const documentHeight = document.documentElement.scrollHeight;
            screen.style.height = documentHeight+'px'
        // 加幕布
            screen.style.display = 'block';
            // 渲染购物车
            resetShoppingCar()
        });


        //购物车数据刷新
       function resetShoppingCar(){
            //筛选被用户选中的商品数据
            
            const selectedGoods = goodsData.filter(item => item.userSelected > 0);
            console.log(selectedGoods);
            document.querySelector('table').innerHTML =" <th>商品图片</th>  <th>商品名称</th>  <th>商品价格</th> <th>商品数量</th>" + selectedGoods.map(item=>`
                <tr>
                    <td class="goodsImg">  <img src=${item.imgURL} alt=""></td>
                    <td class="goodsName">${item.discription}</td>
                    <td class="goodsPrice"><img id=${item.id} class="left" src="./icon/减号.png" alt="">${item.price}<img id=${item.id}  class="right" src="./icon/加号.png" alt=""></td>
                    <td class="count">${item.userSelected}</td>
                </tr>
            `).join("")

            // 加
           let addarr =  document.querySelectorAll('.right')
            for (let i = 0; i < addarr.length; i++) {
                const element = addarr[i];
                element.addEventListener('click',()=>{
                    // console.log(element.id);
                    let goodsId = 'goodsCount' + element.id;
                    // 调用加
                    increaseCount(goodsId,element.id)
                    resetShoppingCar()
                })
            }
        
            // 减
             let dearr =  document.querySelectorAll('.left')
            for (let i = 0; i < dearr.length; i++) {
                const element = dearr[i];
                element.addEventListener('click',()=>{
                    // console.log(element.id);
                    let goodsId = 'goodsCount' + element.id;
                    // 调用加
                    decreaseCount(goodsId,element.id)
                   resetShoppingCar()
                })
            }
            // 获取总金额
            let money = 0 
             selectedGoods.forEach(item=>{
                money += parseFloat(item.price) * parseInt(item.userSelected)
            })
            document.querySelector('.money').innerHTML = `${money.toFixed(1)}`
        }

        document.querySelector('.screen').addEventListener('click',(event)=>{
             if (event.target.id != 'shoppingCartDetails') {
                screen.style.display = 'none';
            }
        })
        // 点击 shoppingCartDetails 时阻止事件冒泡
        document.querySelector('#shoppingCartDetails').addEventListener('click', function(event) {
        event.stopPropagation();
        });


        // 结账
        document.querySelector('.jiesuan').addEventListener('click',()=>{
            
        })


   </script>
</html>